package com;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class FormPoster {

    private URL url;

    private QueryString queryString = new QueryString();

    public FormPoster(URL url) {
        if(!url.getProtocol().toLowerCase().startsWith("http"))
            throw new IllegalArgumentException("不支持非http请求");
        this.url = url;
    }

    public void add(String name,String value){

        queryString.add(name,value);

    }

    public InputStream post() throws IOException {

        URLConnection uc = url.openConnection();

        uc.setDoOutput(true);

        try (OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream(),"UTF-8")){

            //System.out.println(queryString);

            out.write(queryString.toString());

            out.write("\r\n");

            out.flush();

        }

        return uc.getInputStream();

    }

    public static void main(String[] args) {

        URL url;

        if(args.length > 0){

            try {
                url = new URL(args[0]);
                //System.out.println(url);
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return;
            }

        }else{

            try {
                url = new URL("http://www.cafeaulait.org/books/jnp4/postquery.phtml");
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return;
            }

        }

        FormPoster formPoster = new FormPoster(url);

        formPoster.add("name","Elliotte");

        formPoster.add("email","eh@ibli.com");

        try (InputStream in = formPoster.post()){

            Reader reader = new InputStreamReader(in);

            int c;

            while ((c=reader.read()) != -1){

                System.out.print((char)c);

            }

            System.out.println();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
